<?php

namespace app\admin\service;

use app\admin\dao\MemberDao;
use app\admin\model\UM as UM;
use app\common\model\Member;
use ShidianUtil\Exception\DataNotExistException;
use think\Collection;
use think\exception\ValidateException;

/**
 * Class LawyerSvipService
 * @package app\admin\service
 */
class LawyerSvipService
{
    // dao
    private MemberDao $memberDao;

    public function __construct(MemberDao $memberDao)
    {
        $this->memberDao = $memberDao;
    }

    /**
     * SVIP律师列表
     * @param UM|null $user
     * @param int|null $page
     * @param int|null $page_size
     * @return Collection
     */
    public function index(?UM $user, ?int $page = null, ?int $page_size = null): Collection
    {
        //这里如果要修改查询，建议把查询放到dao层去
        return $this->memberDao->selectSvip($page, $page_size);
    }

    /**
     * 更新
     * @param UM $user
     * @param int $id
     * @param array $params
     * @return void
     */
    public function modify(UM $user, int $id, array $params): void
    {
        $svip = ($params['svip'] ?? 1) == 1 ? 1 : 0;
        $svipProvincesIds = $params['svipProvincesIds'] ?? [];

        if ($svip == 1 && empty($svipProvincesIds)) {
            throw new ValidateException('请选择省份');
        }

        //这里如果要修改查询，建议把查询就放到这里
        $record = Member::field(true)->where('id', $id)->find();

        if (is_null($record)) {
            throw new DataNotExistException('该律师不存在或已被删除');
        }

        if ($record->type != 1) {
            throw new ValidateException('请选择一个正确的律师');
        }

        $record->svip = $svip;
        $record->svipTime = time();
        $record->save();

        if ($record->svip == 0) {
            $svipProvincesIds = [];
        }

        $record->svipProvinces()->sync($svipProvincesIds);

        // 尝试添加保证金账户
        if ($record->svip == 1) {
            try {
                $record->margin()->save([], false);
            } catch (\Exception $exception) {
                // 允许插入失败，表示已经有账户了
            }
        }
    }
}
